package com.example.administrator.myapplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class  MainActivity extends Activity {
    //用于备忘录文件
    private ListView lv;
    private sqlListDBConnect sd;
    private static int page_no = 1,page_count = 0,count = 0;
    private Button btnAdd,btnFirst,btnEnd,btnNext,btnBefor;
    //适配器
    private SimpleAdapter sa;
    private ProgressBar m_progressBar;
    private ActivityManager am;
    private int page_size = 8;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

//       FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });

        //设施显示进度条
        setProgressBarVisibility(true);
        //实例化ActivityMAnager
        am = ActivityManager.getInstance();
        am.addActivity(this);

        //初始化按钮
        btnAdd = (Button)findViewById(R.id.button);
        btnFirst = (Button)findViewById(R.id.btnFirst);
        btnBefor = (Button)findViewById(R.id.btnBefor);
        btnNext = (Button)findViewById(R.id.btnNext);
        btnEnd = (Button)findViewById(R.id.btnBottom);

        //初始化进度天
        m_progressBar = (ProgressBar)findViewById(R.id.progressBar);

        lv = (ListView) findViewById(R.id.ListView);

        sd = new sqlListDBConnect(MainActivity.this);


        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String,Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
                Intent intent  = new Intent();
                intent.putExtra("noteID",map.get("noteID").toString());
                intent.setClass(MainActivity.this,Lookover.class);
                startActivity(intent);
            }
        });

        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final Map<String,Object> map = (Map<String, Object>) parent.getItemAtPosition(position);
                AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
                adb.setTitle(map.get("noteName").toString());
                adb.setItems(new String[]{"删除", "修改"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch(which){
                            case 0:
                                //删除操作
                                SQLiteDatabase sdb = sd.getReadableDatabase();
                                sdb.delete("note","noteID = ?",new String[]{map.get("noteID").toString()});
                                Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                                sdb.close();
                                fenye();
                                break;
                            case 1:
                                Intent intent = new Intent();
                                intent.putExtra("noteID",map.get("noteID").toString());
                                intent.setClass(MainActivity.this,AddActivity.class);
                                startActivity(intent);
                                break;


                        }
                    }
                });
                adb.show();
                return true;
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //显示进度条
                m_progressBar.setVisibility(View.VISIBLE);
                m_progressBar.setProgress(0);
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AddActivity.class);
                startActivity(intent);

            }
        });


//        btnAdd = (Button)findViewById(R.id.button);
//        btnFirst = (Button)findViewById(R.id.btnFirst);
//        btnBefor = (Button)findViewById(R.id.btnBefor);
//        btnNext = (Button)findViewById(R.id.btnNext);
//        btnEnd = (Button)findViewById(R.id.btnBottom);
        //进入首页
        btnFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(page_no == 1){
                    Toast.makeText(MainActivity.this,"已经是首页",Toast.LENGTH_SHORT).show();

                }
                else{
                    page_no = 1;
                }
                fenye();
            }
        });

        //设置下一页
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(page_no == page_count){
                    Toast.makeText(MainActivity.this,"已经是最后一页",Toast.LENGTH_SHORT).show();
                }
                else{
                    page_no +=1;
                }
                fenye();
            }
        });

        //设置上一页
        btnBefor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(page_no == 1)
                    Toast.makeText(MainActivity.this,"已经是首页",Toast.LENGTH_SHORT).show();
                else
                    page_no -=1;
                fenye();
            }
        });

        //设置最后一页
        btnEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 if(page_no == page_count)
                     Toast.makeText(MainActivity.this,"已经是最后一页",Toast.LENGTH_SHORT).show();
                 else
                     page_no = page_count;
                 fenye();
            }

        });
         fenye();
    }

    public void fenye(){
        SQLiteDatabase sdb = sd.getReadableDatabase();
        count  = 0;
        Cursor c1 = sdb.query("note",new String[]{"noteID","noteName","noteTime"},null,null,null,null,"noteID asc");
        while(c1.moveToNext()){
            int noteid = c1.getInt(c1.getColumnIndex("noteID"));
            if(noteid>count){
                //ID == count?
                count = noteid;
            }
            c1.close();
            //get total pages count
            page_count = count%page_size == 0?count/page_size : count/page_size+1;

            if(page_no <1)
                page_no =1;

            if(page_no  >page_count)
                page_no = page_count;

        }

        Cursor c = sdb.rawQuery("select noteID,noteName,noteTime from note limit ?,?;",new String[]{
                (page_no-1)*page_size+"",page_no*page_size+""
        });
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        while(c.moveToNext()){
            Map<String,Object> map = new HashMap<String,Object>();
            //备忘录的名字
            String strName = c.getString(c.getColumnIndex("noteName"));
            //如果字数超过12个字，用...代替
            if(strName.length()>20){
                map.put("noteName",strName.substring(0,20)+"...");

            }
            else{
                map.put("notName",strName);
            }

            map.put("noteTime",c.getString(c.getColumnIndex("noteTime")));
            map.put("noteID",c.getString(c.getColumnIndex("noteID")));

            //将map添加到list中
            list.add(map);


        }
        c.close();
        sdb.close();

        if(count>0){
            //新建一个适配器
            sa = new SimpleAdapter(MainActivity.this,list,R.layout.items,new String []{"noteName"},new int[] {R.id.noteName});
            lv.setAdapter(sa);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        //添加菜单项
        menu.add(0,1,1,"设置铃声");
        menu.add(0,2,2,"推出");
        return  super.onCreateOptionsMenu(menu);

    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return true;
//    }


    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()){
            case 1:
//                Intent intent = new Intent();
//                intent.setClass(MainActivity.this,SetAlarm.class);
//                startActivity(intent);
                break;
            case 2:
                AlertDialog.Builder adb2 = new AlertDialog.Builder(MainActivity.this);
                adb2.setTitle("消息");
                adb2.setMessage("真的要退出吗");
                adb2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        am.exitAllProgress();
                    }
                });
                adb2.setNegativeButton("取消",null);
                //消息提示框显示出来
                adb2.show();
                break;
                default:
                    break;


        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //如果用户想按下BACK键
        if(keyCode == KeyEvent.KEYCODE_BACK){
            AlertDialog.Builder adb2 = new AlertDialog.Builder(MainActivity.this);
            adb2.setTitle("消息");
            adb2.setMessage("真的要退出吗");
            adb2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    am.exitAllProgress();
                }
            });
            adb2.setNegativeButton("取消",null);
            //消息提示框显示出来
            adb2.show();

        }
        return super.onKeyDown(keyCode, event);
    }
}
